package com.yyq.adms.yyb.advance.bpo.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yyq.adms.util.JxlsUtil;
import com.yyq.adms.util.JxlsVo;
import com.yyq.adms.yyb.advance.bpo.STApplyBpo;
import com.yyq.adms.yyb.advance.dao.STApplyDao;
import com.yyq.adms.yyb.advance.pojo.STApply;
import com.yyq.sos.permission.LoginUser;
import com.yyq.sos.service.BaseBpoImpl;
import com.yyq.sos.util.DepartmentUtil;

/**
 * 科技进步 奖励申报
 * @author 杨应滨
 * @2012-12-7
 *
 */
@Service("STApplyBpo")
@Transactional
public class STApplyBpoImpl extends BaseBpoImpl implements STApplyBpo{
	
	private STApplyDao dao;
	private static final String PROJECT_NAME = "项目名称";
	private static final String DEPARTMENT_IN = "申报单位(内部)";
	private static final String DEPARTMENT_OUT = "申报单位(外部)";
	private static final String PROJECT_FINISH_NAME = "项目完成人";
	private static final String APPLY_LEVEL = "申报等级";
	private static final String APPLY_DATE = "申报时间";
	private static final String JUDGE_CORPORATION = "评审机构";
	private static final String EDITMATERIAL = "编制申报材料";
	private static final String UNITAUDIT = "申报单位审核";
	private static final String COMPANYAUDIT = "公司审核";
	private static final String SEAL = "签字盖章";
	private static final String SUBMISSION = "报审";
	private static final String PUBLICITY = "公示";
	private static final String OFFICIALDOCUMENT = "正式发文";
	private static final String COMMEND = "表彰";
	private static final String BELONGPLATEFORM = "所属平台";
	
	
	
	private static final String FORMAT = "yyyy-MM-dd";
	SimpleDateFormat sdf = new SimpleDateFormat(FORMAT);
	@Resource(name="STApplyDao")
	public void setDao(STApplyDao dao) {
		this.dao = dao;
		setBaseDao(dao);
	}


	public String validateBatchAdd(List<Map<String, JxlsVo>> srcData, List<STApply> list,Map<String, Object> vMap, 
			LoginUser user, List<Map<String, JxlsVo>> otherOrgRepeatData) {
		processVMap(vMap);
		StringBuffer errMsg = new StringBuffer();
		Map<String,Integer> contentRepeat=new HashMap<String,Integer>();
		int index=0;
		for (Map<String, JxlsVo> map : srcData) {
			boolean flag = validateData(index,srcData,errMsg, map,list,contentRepeat,user,otherOrgRepeatData);
			index++;
		}
		return errMsg.toString();
	}
	
	private void processVMap(Map<String, Object> vMap){
		vMap.put(PROJECT_NAME, 1);
		vMap.put(DEPARTMENT_IN, 2);
		vMap.put(DEPARTMENT_OUT, 3);
		vMap.put(PROJECT_FINISH_NAME, 4);
		vMap.put(APPLY_LEVEL, 5);
		vMap.put(APPLY_DATE, 6);
		vMap.put(JUDGE_CORPORATION, 7);
		vMap.put(EDITMATERIAL, 8);
		vMap.put(UNITAUDIT, 9);
		vMap.put(COMPANYAUDIT, 10);
		vMap.put(SEAL, 11);
		vMap.put(SUBMISSION, 12);
		vMap.put(PUBLICITY, 13);
		vMap.put(OFFICIALDOCUMENT, 14);
		vMap.put(COMMEND, 15);
		vMap.put(BELONGPLATEFORM, 16);
	}

	private boolean validateData(int index, List<Map<String,JxlsVo>> srcData, StringBuffer errMsg, Map<String, JxlsVo> map,List list,
			Map<String,Integer> contentRepeat,LoginUser user, List<Map<String,JxlsVo>> otherOrgRepeatData) {
		JxlsVo projectNameJVo = map.get(PROJECT_NAME);
		JxlsVo departmentInJVo = map.get(DEPARTMENT_IN);
		JxlsVo departmentOutJVo = map.get(DEPARTMENT_OUT);
		JxlsVo projectFinishNameJVo = map.get(PROJECT_FINISH_NAME);
		JxlsVo applyLevelJVo = map.get(APPLY_LEVEL);
		JxlsVo applyDateJVo = map.get(APPLY_DATE);
		JxlsVo judgeCorporationJVo = map.get(JUDGE_CORPORATION);
		JxlsVo editmaterialJVo = map.get(EDITMATERIAL);
		JxlsVo unitauditJVo = map.get(UNITAUDIT);
		JxlsVo companyauditJVo = map.get(COMPANYAUDIT);
		JxlsVo sealJVo = map.get(SEAL);
		JxlsVo submissionJVo = map.get(SUBMISSION);
		JxlsVo publicityJVo = map.get(PUBLICITY);
		JxlsVo officialdocumentJVo = map.get(OFFICIALDOCUMENT);
		JxlsVo commendJVo = map.get(COMMEND);
		JxlsVo belongPlateFormIDJVo = map.get(BELONGPLATEFORM);
		boolean flag = true;
		String projectContent = projectNameJVo.getContent();
		String applyDateContent = applyDateJVo.getContent();
		if(!projectContent.equals("") && applyDateContent.length()>4){
			String year = applyDateContent.substring(0,4);
			String key = projectContent+year;
			boolean isRepeatDB = checkRepeatDB(projectContent,year,user);
			if(isRepeatDB){
				JxlsVo indexMsg = new JxlsVo();
				indexMsg.setContent("第"+projectNameJVo.getRow()+"行(项目名称+申报年度)数据与数据库重复了");
				indexMsg.setRow(projectNameJVo.getRow());
				map.put("excelIndexMsg", indexMsg);
				otherOrgRepeatData.add(map);
				//return false;
			}
			if(contentRepeat.containsKey(key)){
				int index2 = projectNameJVo.getRow()-contentRepeat.get(key);
				Map<String,JxlsVo> tempMap = srcData.get(index-index2);
				JxlsVo indexMsgPre = new JxlsVo();
				indexMsgPre.setContent("第"+contentRepeat.get(key)+"行(项目名称+申报年度)与第"+projectNameJVo.getRow()+"行数据重复了");
				indexMsgPre.setRow(contentRepeat.get(key));
				tempMap.put("excelIndexMsg", indexMsgPre);
				JxlsVo indexMsg = new JxlsVo();
				indexMsg.setContent("第"+projectNameJVo.getRow()+"行(项目名称+申报年度)与第"+contentRepeat.get(key)+"行数据重复了");
				indexMsg.setRow(projectNameJVo.getRow());
				map.put("excelIndexMsg", indexMsg);
				otherOrgRepeatData.add(tempMap);
				otherOrgRepeatData.add(map);
				//errMsg.append("第").append(projectNameJVo.getRow()).append("行(项目名称+申报年度)")
				//.append("与第").append(contentRepeat.get(key)).append("行的(项目名称+申报年度)出现重复了!<br/>");
			}else{
				contentRepeat.put(key, projectNameJVo.getRow());
			}
		}
		STApply vo = new STApply();
		vo.setProjectName(projectContent);
		if(!departmentOutJVo.getContent().equals("") && departmentInJVo.getContent().equals("")){
			vo.setDepartment(departmentOutJVo.getContent());
		}else if(!departmentOutJVo.getContent().equals("") && !departmentInJVo.getContent().equals("")){
			vo.setDepartment(departmentInJVo.getContent()+","+departmentOutJVo.getContent());
		}else if(departmentOutJVo.getContent().equals("") && !departmentInJVo.getContent().equals("")){
			vo.setDepartment(departmentInJVo.getContent());
		}
//		vo.setSentDep(departmentInJVo.getContent());
		processSentDep(departmentInJVo.getContent(),errMsg,departmentInJVo,vo);
		vo.setProjectFinishName(projectFinishNameJVo.getContent());
		vo.setApplyLevel(applyLevelJVo.getContent());
		
		try {
			vo.setApplyDate(sdf.parse(applyDateContent));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		vo.setJudgeCorporation(judgeCorporationJVo.getContent());
		vo.setBelongPlateFormID(belongPlateFormIDJVo.getContent());
		
		validateBlank(errMsg, projectNameJVo,PROJECT_NAME);
		validateBlank(errMsg, departmentInJVo,DEPARTMENT_IN);
		validateBlank(errMsg, applyLevelJVo,APPLY_LEVEL);
		validateBlank(errMsg, applyDateJVo,APPLY_DATE);
		validateBlank(errMsg, judgeCorporationJVo,JUDGE_CORPORATION);
		validateBlank(errMsg, belongPlateFormIDJVo,BELONGPLATEFORM);
		
		validateDate(errMsg, applyDateJVo,APPLY_DATE,FORMAT);
		validateDate(errMsg, editmaterialJVo,"编制申报材料",FORMAT);
		validateDate(errMsg, unitauditJVo,"申报单位审核",FORMAT);
		validateDate(errMsg, companyauditJVo,"公司审核",FORMAT);
		validateDate(errMsg, sealJVo,"签字盖章",FORMAT);
		validateDate(errMsg, submissionJVo,"报审",FORMAT);
		validateDate(errMsg, publicityJVo,"公示",FORMAT);
		validateDate(errMsg, officialdocumentJVo,"正式发文",FORMAT);
		validateDate(errMsg, commendJVo,"表彰",FORMAT);
		
		validateBlank(errMsg, editmaterialJVo,"编制申报材料");
		if(!commendJVo.getContent().equals("")){
			vo.setCommend(commendJVo.getContent());
			vo.setJudgeState("表彰");
			validateBlank(errMsg, unitauditJVo,"申报单位审核");
			validateBlank(errMsg, companyauditJVo,"公司审核");
			validateBlank(errMsg, sealJVo,"签字盖章");
			validateBlank(errMsg, submissionJVo,"报审");
			validateBlank(errMsg, publicityJVo,"公示");
			validateBlank(errMsg, officialdocumentJVo,"正式发文");
		}
		if(!officialdocumentJVo.getContent().equals("")){
			vo.setOfficialdocument(officialdocumentJVo.getContent());
			if(vo.getJudgeState() == null || "".equals(vo.getJudgeState())){
				vo.setJudgeState("正式发文");
			}
			validateBlank(errMsg, unitauditJVo,"申报单位审核");
			validateBlank(errMsg, companyauditJVo,"公司审核");
			validateBlank(errMsg, sealJVo,"签字盖章");
			validateBlank(errMsg, submissionJVo,"报审");
			validateBlank(errMsg, publicityJVo,"公示");
		}
		if(!publicityJVo.getContent().equals("")){
			vo.setPublicity(publicityJVo.getContent());
			if(vo.getJudgeState() == null || "".equals(vo.getJudgeState())){
				vo.setJudgeState("公示");
			}
			validateBlank(errMsg, unitauditJVo,"申报单位审核");
			validateBlank(errMsg, companyauditJVo,"公司审核");
			validateBlank(errMsg, sealJVo,"签字盖章");
			validateBlank(errMsg, submissionJVo,"报审");
		}
		if(!submissionJVo.getContent().equals("")){
			vo.setSubmission(submissionJVo.getContent());
			if(vo.getJudgeState() == null || "".equals(vo.getJudgeState())){
				vo.setJudgeState("报审");
			}
			validateBlank(errMsg, unitauditJVo,"申报单位审核");
			validateBlank(errMsg, companyauditJVo,"公司审核");
			validateBlank(errMsg, sealJVo,"签字盖章");
		}
		if(!sealJVo.getContent().equals("")){
			vo.setSeal(sealJVo.getContent());
			if(vo.getJudgeState() == null || "".equals(vo.getJudgeState())){
				vo.setJudgeState("签字盖章");
			}
			validateBlank(errMsg, unitauditJVo,"申报单位审核");
			validateBlank(errMsg, companyauditJVo,"公司审核");
		}
		if(!companyauditJVo.getContent().equals("")){
			vo.setCompanyaudit(companyauditJVo.getContent());
			if(vo.getJudgeState() == null || "".equals(vo.getJudgeState())){
				vo.setJudgeState("公司审核");
			}
			validateBlank(errMsg, unitauditJVo,"申报单位审核");
		}
		if(!unitauditJVo.getContent().equals("")){
			vo.setUnitaudit(unitauditJVo.getContent());
			if(vo.getJudgeState() == null || "".equals(vo.getJudgeState())){
				vo.setJudgeState("申报单位审核");
			}
		}
		if(vo.getJudgeState() == null || "".equals(vo.getJudgeState())){
			vo.setJudgeState("编制申报材料");
		}
		vo.setEditmaterial(editmaterialJVo.getContent());
		list.add(vo);
		return flag;
	}

	private void processSentDep(String content, StringBuffer errMsg, JxlsVo vo, STApply obj) {
		if(content != null && !content.equals("")){
			String[] str = content.split("[,，]");
			String sentDepStr = "";
			String sentDepName = "";
			for(int i=0;i<str.length;i++){
				Long sentDeptId = DepartmentUtil.getInstance().getValue(str[i]);
				if(sentDeptId != null){
					if(i==str.length){
						sentDepStr += sentDeptId;
						sentDepName += str[i];
					}else{
						sentDepStr += sentDeptId+",";
						sentDepName += str[i]+(i<(str.length-1)?",":"");
					}
				}else{
					JxlsUtil.preErrMsg(errMsg,vo ,DEPARTMENT_IN);
					errMsg.append("的").append(str[i]).append("不正确").append("<br/>");
				}
			}
			if(!sentDepStr.equals("") && obj != null){
				obj.setSentDep(sentDepStr);
				obj.setSentDepName(sentDepName);
			}
		}
	}


	private boolean checkRepeatDB(String projectContent, String year,
			LoginUser user) {
		String hql = "from STApply obj where  " +
		"(obj.maintainDep="+user.getOrgId()+" or " +
		"EXISTS(from RecordSentDep rsd where obj.id=rsd.sourceRecordId " +
		"and rsd.yyqTableName='"+dao.getTableName(STApply.class)+"' and rsd.sentDepId="+user.getOrgId()+"))" +
		" and projectName='"+projectContent+"' and applyDate like '%"+year+"%'";
		long count = dao.count(hql);
		return count > 0 ? true : false;
	}


	private void validateBlank(StringBuffer errMsg, JxlsVo jVo,String key) {
		if(jVo.getContent().equals("")){
			JxlsUtil.preErrMsg(errMsg, jVo, key);
			errMsg.append("不能为空").append("<br/>");
		}
	}
	
	private void setJudgeStateErrMsg(StringBuffer errMsg, JxlsVo jVo,String key){
		JxlsUtil.preErrMsg(errMsg, jVo, key);
		errMsg.append("评审阶段的").append(key).append("阶段的前面时间不能为空!").append("<br/>");
	}
	private void validateDate(StringBuffer errMsg, JxlsVo jVo,String key,String format){
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		if(!jVo.getContent().equals("")){
			Date d = null;
			try {
				d = sdf.parse(jVo.getContent());
			} catch (ParseException e) {
				JxlsUtil.preErrMsg(errMsg, jVo, key);
				errMsg.append(jVo.getContent()).append(":").append("其日期格式不正确(").append(format)
				.append(")<br/>");
			}
			/*
			if(d != null){
				String temp = sdf.format(d);
				if(!temp.equals(jVo.getContent())){
					JxlsUtil.preErrMsg(errMsg, jVo, key);
					errMsg.append(jVo.getContent()).append(":").append("其日期格式不正确(").append(format)
					.append(")<br/>");
				}
			}
			*/
		}
	}
}
